/*
 * Created on 3-Dec-2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.mtdownload.download;

import java.io.Serializable;


/**
 * This class is responsible to calculate the speed, eta and other informations for a task.
 * It must have only one instance per download task 
 * @author sergiu
 */
public class TaskInfoUpdater implements Serializable{

	/**
	 * Comment for <code>serialVersionUID</code>
	 */
	private static final long serialVersionUID = 3258417213827593014L;
	long measuredBytes=0;
	
	/**
	 * 
	 */
	public TaskInfoUpdater() {
		super();
		measuredBytes=0;		
	}
	
	public DownloadTask updateTaskInfo(DownloadTask task,BytesCounter counter,long downloadFileLength){
		//check out to see how many bytes have been read since our last run
		long completedBytes=counter.getCompletedBytes();
		//System.out.println(completedBytes);
		long diff=completedBytes-measuredBytes;
		measuredBytes=completedBytes;
		//ETA is measured calculating how many bytes we have to download at the current speed
		long eta=Long.MAX_VALUE;
		if(diff>0 && task.getFileLength()>0){
			eta=(task.getFileLength()-task.getCompletedBytes())/diff;	
		}else{
			eta=-1;
		}
		//we have now "eta" number of seconds to wait
		
		//this means that we have a speed of "diff" per second
		//update the task and the view
		task.setSpeed(diff);
		task.setEta(eta);
		task.setThreadsSpeed(new long[task.getMasterThread().getThreads().size()]);
		for(DownloadThread thread:task.getMasterThread().getThreads()){
			task.setSpeedForThread(thread.getIndex(),thread.getThreadSpeed());
		}
		if(downloadFileLength>0){
			task.setPercentComplete((double)counter.getCompletedBytes()/(double)downloadFileLength);
		}else{
			task.setPercentComplete(-1);
		}
		task.setElapsed(task.getElapsed()+1);
		return task;
	}

}
